<template>
  <div class="activities-page">
    <!-- 页面标题 -->
    <t-card class="header-card">
      <div class="card-header">
        <h2 class="page-title">活动管理</h2>
        <t-button theme="primary" @click="handleAddActivity">
          <template #icon><t-icon name="add" /></template>
          新增活动
        </t-button>
      </div>
    </t-card>

    <!-- 搜索和筛选 -->
    <t-card class="search-card">
      <t-row :gutter="[16, 16]">
        <t-col :xs="24" :sm="12" :md="6">
          <t-input v-model="searchParams.keyword" placeholder="搜索活动名称" clearable>
            <template #suffix><t-icon name="search" /></template>
          </t-input>
        </t-col>
        <t-col :xs="24" :sm="12" :md="6">
          <t-select v-model="searchParams.category" placeholder="活动类型" clearable>
            <t-option v-for="item in categoryOptions" :key="item.value" :value="item.value" :label="item.label" />
          </t-select>
        </t-col>
        <t-col :xs="24" :sm="12" :md="6">
          <t-select v-model="searchParams.status" placeholder="活动状态" clearable>
            <t-option v-for="item in statusOptions" :key="item.value" :value="item.value" :label="item.label" />
          </t-select>
        </t-col>
        <t-col :xs="24" :sm="12" :md="6" class="search-buttons">
          <t-space>
            <t-button theme="primary" @click="handleSearch">
              <template #icon><t-icon name="search" /></template>
              搜索
            </t-button>
            <t-button theme="default" @click="resetSearch">
              重置
            </t-button>
          </t-space>
        </t-col>
      </t-row>
    </t-card>

    <!-- 活动列表 -->
    <t-card class="table-card">
      <t-loading :loading="loading" style="width: 100%">
        <t-table
          :data="activities"
          :columns="columns"
          :row-key="(row) => row.id"
          stripe
          :max-height="600"
          :pagination="pagination"
          @page-change="onPageChange"
        >
          <template #poster="{ row }">
            <div class="activity-poster-container">
              <img :src="row.posterUrl" :alt="row.title" class="activity-poster" />
            </div>
          </template>
          <template #timeRange="{ row }">
            <div>
              {{ formatDate(row.startTime) }} - {{ formatDate(row.endTime) }}
            </div>
          </template>
          <template #status="{ row }">
            <t-tag :theme="getStatusTheme(row.status)" variant="light">
              {{ getStatusLabel(row.status) }}
            </t-tag>
          </template>
          <template #signupCount="{ row }">
            {{ row.signupCount }} / {{ row.maxParticipants }}
            <t-progress
              :percentage="Math.round((row.signupCount / row.maxParticipants) * 100)"
              :color="getProgressColor(row.signupCount, row.maxParticipants)"
              :track-color="'#e9e9e9'"
              :height="8"
              :stroke-width="8"
            />
          </template>
          <template #createTime="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
          <template #operation="{ row }">
            <t-space size="small">
              <t-tooltip content="查看报名名单">
                <t-button variant="text" theme="primary" size="small" @click="handleViewSignups(row)">
                  <template #icon><t-icon name="user-list" /></template>
                </t-button>
              </t-tooltip>
              <t-button variant="text" theme="primary" size="small" @click="handleEditActivity(row)">
                <template #icon><t-icon name="edit" /></template>
                编辑
              </t-button>
              <t-button
                v-if="canChangeStatus(row.status)"
                :theme="getActionTheme(row.status)"
                variant="text"
                size="small"
                @click="handleChangeStatus(row)"
              >
                <template #icon>
                  <t-icon :name="getActionIcon(row.status)" />
                </template>
                {{ getActionLabel(row.status) }}
              </t-button>
              <t-popconfirm v-if="row.status !== 'completed'" content="确认取消该活动吗？" @confirm="handleCancelActivity(row)">
                <t-button theme="danger" variant="text" size="small">
                  <template #icon><t-icon name="close-circle" /></template>
                  取消活动
                </t-button>
              </t-popconfirm>
              <t-popconfirm content="确认删除该活动吗？" @confirm="handleDeleteActivity(row)">
                <t-button theme="danger" variant="text" size="small">
                  <template #icon><t-icon name="delete" /></template>
                  删除
                </t-button>
              </t-popconfirm>
            </t-space>
          </template>
        </t-table>
      </t-loading>
    </t-card>

    <!-- 活动表单对话框 -->
    <t-dialog
      v-model:visible="dialogVisible"
      :header="isEdit ? '编辑活动' : '新增活动'"
      width="800px"
      :footer="false"
      @close="resetForm"
    >
      <t-form
        ref="form"
        :data="formData"
        :rules="rules"
        :label-width="100"
        @submit="handleSubmit"
      >
        <t-form-item label="活动名称" name="title">
          <t-input v-model="formData.title" placeholder="请输入活动名称" />
        </t-form-item>
        
        <t-row :gutter="[16, 16]">
          <t-col :span="12">
            <t-form-item label="活动类型" name="category">
              <t-select v-model="formData.category" placeholder="请选择活动类型">
                <t-option v-for="item in categoryOptions" :key="item.value" :value="item.value" :label="item.label" />
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item label="活动状态" name="status">
              <t-select v-model="formData.status" placeholder="请选择活动状态">
                <t-option v-for="item in editStatusOptions" :key="item.value" :value="item.value" :label="item.label" />
              </t-select>
            </t-form-item>
          </t-col>
        </t-row>
        
        <t-form-item label="活动海报" name="posterUrl">
          <t-upload
            v-model="formData.posterFile"
            theme="image"
            :before-upload="handleBeforeUpload"
            accept="image/*"
          >
            <template #tip>
              <p class="tip-text">支持jpg/png格式，建议尺寸800*450px，大小不超过2M</p>
            </template>
          </t-upload>
        </t-form-item>
        
        <t-row :gutter="[16, 16]">
          <t-col :span="12">
            <t-form-item label="开始时间" name="startTime">
              <t-date-picker
                v-model="formData.startTime"
                mode="date"
                enableTimePicker
                :clearable="false"
                format="YYYY-MM-DD HH:mm"
              />
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item label="结束时间" name="endTime">
              <t-date-picker
                v-model="formData.endTime"
                mode="date"
                enableTimePicker
                :clearable="false"
                format="YYYY-MM-DD HH:mm"
              />
            </t-form-item>
          </t-col>
        </t-row>
        
        <t-row :gutter="[16, 16]">
          <t-col :span="12">
            <t-form-item label="活动地点" name="location">
              <t-input v-model="formData.location" placeholder="请输入活动地点" />
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item label="人数限制" name="maxParticipants">
              <t-input-number v-model="formData.maxParticipants" :min="1" :max="1000" />
            </t-form-item>
          </t-col>
        </t-row>
        
        <t-form-item label="活动简介" name="description">
          <t-textarea
            v-model="formData.description"
            placeholder="请输入活动简介"
            :autosize="{ minRows: 3, maxRows: 5 }"
            :max-length="500"
          />
        </t-form-item>
        
        <t-form-item label="活动标签" name="tags">
          <t-tag-input
            v-model="formData.tags"
            placeholder="输入标签后按Enter确认"
            :max-tags="5"
            clearable
          />
        </t-form-item>
        
        <t-row :gutter="[16, 16]">
          <t-col :span="12">
            <t-form-item label="报名费用" name="price">
              <t-input-adornment prepend="￥">
                <t-input-number v-model="formData.price" :min="0" :max="10000" :step="10" />
              </t-input-adornment>
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item label="联系电话" name="contactPhone">
              <t-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
            </t-form-item>
          </t-col>
        </t-row>
        
        <t-form-item>
          <t-space>
            <t-button theme="default" @click="dialogVisible = false">取消</t-button>
            <t-button theme="primary" type="submit" :loading="submitting">确定</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>

    <!-- 报名名单对话框 -->
    <t-dialog
      v-model:visible="signupDialogVisible"
      :header="selectedActivity ? selectedActivity.title + ' - 报名名单' : '报名名单'"
      width="800px"
      :footer="false"
    >
      <t-table
        v-if="selectedActivity"
        :data="signupList"
        :columns="signupColumns"
        :row-key="(row) => row.id"
        stripe
      >
        <template #gender="{ row }">
          {{ row.gender === 'male' ? '男' : '女' }}
        </template>
        <template #signupTime="{ row }">
          {{ formatDateTime(row.signupTime) }}
        </template>
        <template #payStatus="{ row }">
          <t-tag :theme="row.payStatus === 'paid' ? 'success' : 'warning'" variant="light">
            {{ row.payStatus === 'paid' ? '已支付' : '未支付' }}
          </t-tag>
        </template>
        <template #operation="{ row }">
          <t-space>
            <t-popconfirm content="确认取消该用户报名吗？" @confirm="handleCancelSignup(row)">
              <t-button theme="danger" variant="text" size="small">
                <template #icon><t-icon name="remove" /></template>
                取消报名
              </t-button>
            </t-popconfirm>
          </t-space>
        </template>
      </t-table>
      <template #footer>
        <t-button theme="primary" @click="signupDialogVisible = false">关闭</t-button>
      </template>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import dayjs from 'dayjs'

// 定义类型接口
interface Activity {
  id: string;
  title: string;
  posterUrl: string;
  category: string;
  startTime: string;
  endTime: string;
  location: string;
  maxParticipants: number;
  signupCount: number;
  description: string;
  tags: string[];
  price: number;
  contactPhone: string;
  status: 'upcoming' | 'registering' | 'ongoing' | 'completed' | 'canceled';
  createTime: string;
}

interface SignupInfo {
  id: string;
  name: string;
  gender: 'male' | 'female';
  phone: string;
  idCard: string;
  signupTime: string;
  payStatus: 'paid' | 'unpaid';
  remark: string;
}

interface CategoryOption {
  label: string;
  value: string;
}

interface StatusOption {
  label: string;
  value: string;
}

interface StatusMap {
  [key: string]: string;
}

// 活动类型选项
const categoryOptions: CategoryOption[] = [
  { label: '户外运动', value: 'outdoor' },
  { label: '康养讲座', value: 'lecture' },
  { label: '文化体验', value: 'culture' },
  { label: '健康饮食', value: 'food' },
  { label: '亲子活动', value: 'family' },
]

// 活动状态选项
const statusOptions: StatusOption[] = [
  { label: '未开始', value: 'upcoming' },
  { label: '报名中', value: 'registering' },
  { label: '进行中', value: 'ongoing' },
  { label: '已结束', value: 'completed' },
  { label: '已取消', value: 'canceled' },
]

// 编辑状态下的状态选项（去掉已取消）
const editStatusOptions = statusOptions.filter(item => item.value !== 'canceled')

// 列定义
const columns = [
  { colKey: 'poster', title: '活动海报', width: 100 },
  { colKey: 'title', title: '活动名称', width: 180 },
  { colKey: 'category', title: '类型', width: 100, cell: ({ row }: { row: Activity }) => {
    const found = categoryOptions.find(item => item.value === row.category)
    return found ? found.label : row.category
  }},
  { colKey: 'timeRange', title: '活动时间', width: 220 },
  { colKey: 'location', title: '活动地点', width: 150 },
  { colKey: 'signupCount', title: '报名情况', width: 120 },
  { colKey: 'price', title: '费用(元)', width: 80 },
  { colKey: 'status', title: '状态', width: 100 },
  { colKey: 'operation', title: '操作', fixed: 'right', width: 200 },
]

// 报名信息列定义
const signupColumns = [
  { colKey: 'name', title: '姓名', width: 100 },
  { colKey: 'gender', title: '性别', width: 60 },
  { colKey: 'phone', title: '手机号', width: 120 },
  { colKey: 'idCard', title: '身份证号', width: 150, cell: ({ row }: { row: SignupInfo }) => {
    if (!row.idCard) return '-'
    // 身份证号脱敏显示，保留前4位和后4位
    return row.idCard.replace(/^(.{4})(.*)(.{4})$/, '$1****$3')
  }},
  { colKey: 'signupTime', title: '报名时间', width: 150 },
  { colKey: 'payStatus', title: '支付状态', width: 100 },
  { colKey: 'remark', title: '备注', width: 200 },
  { colKey: 'operation', title: '操作', width: 120 },
]

// 状态管理
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const signupDialogVisible = ref(false)
const isEdit = ref(false)
const selectedActivity = ref<Activity | null>(null)

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  pageSizeOptions: [5, 10, 20, 50],
  showJumper: true,
  showPageSize: true,
})

// 搜索参数
const searchParams = reactive({
  keyword: '',
  category: '',
  status: '',
})

// 活动数据
const activities = ref<Activity[]>([
  {
    id: '1',
    title: '夏日瑜伽健康营',
    posterUrl: 'https://tdesign.gtimg.com/site/source/figma-pc.png',
    category: 'outdoor',
    startTime: '2024-07-15 09:00',
    endTime: '2024-07-20 17:00',
    location: '贵州四季康养中心瑜伽馆',
    maxParticipants: 30,
    signupCount: 18,
    description: '为期5天的瑜伽健康营，每日开展专业瑜伽课程，搭配健康饮食指导和自然疗愈活动，帮助参与者恢复身心平衡。',
    tags: ['瑜伽', '健康', '放松'],
    price: 1280,
    contactPhone: '13912345678',
    status: 'registering',
    createTime: '2024-06-01',
  },
  {
    id: '2',
    title: '中医养生讲座',
    posterUrl: 'https://tdesign.gtimg.com/site/source/figma-pc.png',
    category: 'lecture',
    startTime: '2024-06-30 14:00',
    endTime: '2024-06-30 16:30',
    location: '贵州四季康养中心多功能厅',
    maxParticipants: 100,
    signupCount: 78,
    description: '特邀国医大师刘长春教授讲解中医养生之道，包括四季养生、食疗保健、传统中医调理等内容。',
    tags: ['中医', '养生', '讲座'],
    price: 99,
    contactPhone: '13887654321',
    status: 'upcoming',
    createTime: '2024-06-05',
  },
  {
    id: '3',
    title: '贵州苗族文化体验',
    posterUrl: 'https://tdesign.gtimg.com/site/source/figma-pc.png',
    category: 'culture',
    startTime: '2024-06-10 10:00',
    endTime: '2024-06-10 17:00',
    location: '贵州苗族文化村',
    maxParticipants: 50,
    signupCount: 50,
    description: '深入体验贵州苗族文化，包括苗族服饰体验、银饰制作、传统美食品尝、民族歌舞表演等。',
    tags: ['文化', '体验', '苗族'],
    price: 268,
    contactPhone: '13855667788',
    status: 'completed',
    createTime: '2024-05-15',
  },
  {
    id: '4',
    title: '森林徒步解压之旅',
    posterUrl: 'https://tdesign.gtimg.com/site/source/figma-pc.png',
    category: 'outdoor',
    startTime: '2024-06-25 08:00',
    endTime: '2024-06-25 16:00',
    location: '贵州省花溪国家森林公园',
    maxParticipants: 40,
    signupCount: 15,
    description: '在专业导师带领下，进行森林徒步旅行，呼吸负离子丰富的空气，放松身心，缓解都市压力。',
    tags: ['徒步', '森林', '减压'],
    price: 158,
    contactPhone: '13966778899',
    status: 'registering',
    createTime: '2024-06-10',
  },
  {
    id: '5',
    title: '夏日亲子农场',
    posterUrl: 'https://tdesign.gtimg.com/site/source/figma-pc.png',
    category: 'family',
    startTime: '2024-07-05 09:30',
    endTime: '2024-07-05 15:30',
    location: '贵州绿心有机农场',
    maxParticipants: 80,
    signupCount: 25,
    description: '亲子互动农场体验，包括有机蔬果采摘、动物喂养、手工DIY、农耕体验等，增进亲子关系，了解自然农耕。',
    tags: ['亲子', '农场', '自然教育'],
    price: 258,
    contactPhone: '13977889900',
    status: 'registering',
    createTime: '2024-06-15',
  },
])

// 表单数据
interface UploadFile {
  name: string;
  url: string;
}

interface FormData {
  id: string;
  title: string;
  posterFile: UploadFile[];
  posterUrl: string;
  category: string;
  startTime: string;
  endTime: string;
  location: string;
  maxParticipants: number;
  description: string;
  tags: string[];
  price: number;
  contactPhone: string;
  status: string;
}

const formData = reactive<FormData>({
  id: '',
  title: '',
  posterFile: [],
  posterUrl: '',
  category: '',
  startTime: '',
  endTime: '',
  location: '',
  maxParticipants: 50,
  description: '',
  tags: [],
  price: 0,
  contactPhone: '',
  status: 'upcoming',
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入活动名称', type: 'error' },
    { max: 50, message: '活动名称不能超过50个字符', type: 'warning' }
  ],
  category: [
    { required: true, message: '请选择活动类型', type: 'error' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', type: 'error' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', type: 'error' },
    { validator: validateTimeRange, message: '结束时间必须晚于开始时间', type: 'error' }
  ],
  location: [
    { required: true, message: '请输入活动地点', type: 'error' }
  ],
  maxParticipants: [
    { required: true, message: '请输入人数限制', type: 'error' }
  ],
  description: [
    { required: true, message: '请输入活动简介', type: 'error' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', type: 'error' }
  ]
}

// 编辑的活动索引
const editIndex = ref(-1)

// 模拟报名列表数据
const signupList = ref<SignupInfo[]>([])

// 时间范围验证
function validateTimeRange(val: string): boolean {
  if (!formData.startTime || !val) return true
  return new Date(val) > new Date(formData.startTime)
}

// 获取进度条颜色
function getProgressColor(current: number, max: number): string {
  const percentage = current / max
  if (percentage >= 0.8) return '#ff4500' // 报名快满了，红色
  if (percentage >= 0.5) return '#ff9800' // 报名过半，橙色
  return '#00a870' // 报名较少，绿色
}

// 获取状态标签
function getStatusLabel(status: string): string {
  const statusMap: StatusMap = {
    upcoming: '未开始',
    registering: '报名中',
    ongoing: '进行中',
    completed: '已结束',
    canceled: '已取消'
  }
  return statusMap[status] || status
}

// 获取状态对应的主题色
function getStatusTheme(status: string): string {
  const themeMap: StatusMap = {
    upcoming: 'primary',
    registering: 'success',
    ongoing: 'warning',
    completed: 'default',
    canceled: 'danger'
  }
  return themeMap[status] || 'default'
}

// 判断是否可以切换状态
function canChangeStatus(status: string): boolean {
  return ['upcoming', 'registering', 'ongoing'].includes(status)
}

// 获取操作按钮文本
function getActionLabel(status: string): string {
  const labelMap: StatusMap = {
    upcoming: '开始报名',
    registering: '开始活动',
    ongoing: '结束活动'
  }
  return labelMap[status] || ''
}

// 获取操作按钮图标
function getActionIcon(status: string): string {
  const iconMap: StatusMap = {
    upcoming: 'play-circle',
    registering: 'play-circle-stroke',
    ongoing: 'stop-circle-1'
  }
  return iconMap[status] || ''
}

// 获取操作按钮主题色
function getActionTheme(status: string): string {
  const themeMap: StatusMap = {
    upcoming: 'success',
    registering: 'warning',
    ongoing: 'primary'
  }
  return themeMap[status] || 'default'
}

// 搜索
const handleSearch = () => {
  // 实际应该调用API搜索，这里简单模拟
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 800)
}

// 重置搜索
const resetSearch = () => {
  searchParams.keyword = ''
  searchParams.category = ''
  searchParams.status = ''
  handleSearch()
}

// 分页变更
const onPageChange = (pageInfo: { current: number; pageSize: number }) => {
  pagination.current = pageInfo.current
  pagination.pageSize = pageInfo.pageSize
  // 加载数据
  handleSearch()
}

// 日期格式化（只显示日期）
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD')
}

// 日期时间格式化（显示日期和时间）
const formatDateTime = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

// 添加活动
const handleAddActivity = () => {
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

// 编辑活动
const handleEditActivity = (activity: Activity) => {
  isEdit.value = true
  dialogVisible.value = true
  
  // 查找索引
  const index = activities.value.findIndex(item => item.id === activity.id)
  if (index !== -1) {
    editIndex.value = index
    
    // 填充表单数据
    Object.keys(formData).forEach(key => {
      if (key in activity) {
        (formData as any)[key] = (activity as any)[key]
      }
    })
    
    // 如果有海报，添加到上传列表中
    if (activity.posterUrl) {
      formData.posterFile = [{
        name: activity.title,
        url: activity.posterUrl,
      }]
    }
  }
}

// 删除活动
const handleDeleteActivity = (activity: Activity) => {
  const index = activities.value.findIndex(item => item.id === activity.id)
  if (index !== -1) {
    activities.value.splice(index, 1)
    MessagePlugin.success('删除成功')
  }
}

// 取消活动
const handleCancelActivity = (activity: Activity) => {
  const index = activities.value.findIndex(item => item.id === activity.id)
  if (index !== -1) {
    activities.value[index].status = 'canceled'
    MessagePlugin.success('活动已取消')
  }
}

// 切换活动状态
const handleChangeStatus = (activity: Activity) => {
  const index = activities.value.findIndex(item => item.id === activity.id)
  if (index !== -1) {
    const statusTransition: StatusMap = {
      upcoming: 'registering',
      registering: 'ongoing',
      ongoing: 'completed'
    }
    
    const currentStatus = activities.value[index].status
    if (currentStatus in statusTransition) {
      activities.value[index].status = statusTransition[currentStatus] as Activity['status']
      MessagePlugin.success(`活动状态已更新为 ${getStatusLabel(statusTransition[currentStatus])}`)
    }
  }
}

// 查看报名名单
const handleViewSignups = (activity: Activity) => {
  selectedActivity.value = activity
  signupDialogVisible.value = true
  
  // 模拟加载报名数据
  loading.value = true
  setTimeout(() => {
    // 生成随机报名数据
    const count = activity.signupCount
    const list: SignupInfo[] = []
    for (let i = 0; i < count; i++) {
      const isPaid = Math.random() > 0.2 // 80%的概率已支付
      list.push({
        id: `signup_${activity.id}_${i}`,
        name: `用户${i + 1}`,
        gender: Math.random() > 0.5 ? 'male' : 'female',
        phone: `1388888${String(i).padStart(4, '0')}`,
        idCard: i % 5 === 0 ? '' : `4401010199${String(i).padStart(4, '0')}1234`,
        signupTime: dayjs().subtract(Math.floor(Math.random() * 10), 'day').format('YYYY-MM-DD HH:mm:ss'),
        payStatus: isPaid ? 'paid' : 'unpaid',
        remark: i % 3 === 0 ? '有饮食特殊需求' : '',
      })
    }
    signupList.value = list
    loading.value = false
  }, 800)
}

// 取消报名
const handleCancelSignup = (signup: SignupInfo) => {
  // 模拟取消报名
  const index = signupList.value.findIndex(item => item.id === signup.id)
  if (index !== -1) {
    signupList.value.splice(index, 1)
    
    // 更新活动报名人数
    if (selectedActivity.value) {
      const activityIndex = activities.value.findIndex(item => item.id === selectedActivity.value.id)
      if (activityIndex !== -1) {
        activities.value[activityIndex].signupCount--
        selectedActivity.value.signupCount--
      }
    }
    
    MessagePlugin.success('报名已取消')
  }
}

// 表单提交
const handleSubmit = async ({ validateResult }: { validateResult: boolean }) => {
  if (validateResult !== true) return
  
  submitting.value = true
  
  try {
    // 模拟异步操作
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟上传图片
    const posterUrl = formData.posterFile.length > 0
      ? formData.posterFile[0].url || 'https://tdesign.gtimg.com/site/source/figma-pc.png'
      : formData.posterUrl
    
    // 构造保存数据
    const saveData: Activity = {
      id: isEdit.value ? formData.id : `${Date.now()}`,
      title: formData.title,
      posterUrl,
      category: formData.category,
      startTime: formData.startTime,
      endTime: formData.endTime,
      location: formData.location,
      maxParticipants: formData.maxParticipants,
      signupCount: isEdit.value ? activities.value[editIndex.value].signupCount : 0,
      description: formData.description,
      tags: formData.tags,
      price: formData.price,
      contactPhone: formData.contactPhone,
      status: formData.status as Activity['status'],
      createTime: isEdit.value ? activities.value[editIndex.value].createTime : dayjs().format('YYYY-MM-DD'),
    }
    
    // 保存操作
    if (isEdit.value) {
      // 编辑活动
      activities.value.splice(editIndex.value, 1, saveData)
      MessagePlugin.success('保存成功')
    } else {
      // 新增活动
      activities.value.push(saveData)
      MessagePlugin.success('添加成功')
    }
    
    dialogVisible.value = false
  } finally {
    submitting.value = false
  }
}

// 上传前校验
const handleBeforeUpload = (file: File) => {
  // 检查文件类型
  const isImage = /image\/(jpeg|png)/.test(file.type)
  if (!isImage) {
    MessagePlugin.warning('只能上传jpg/png格式图片')
    return false
  }
  
  // 检查文件大小，限制为2MB
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    MessagePlugin.warning('图片大小不能超过2MB')
    return false
  }
  
  return isImage && isLt2M
}

// 重置表单
const resetForm = () => {
  Object.keys(formData).forEach(key => {
    switch (key) {
      case 'posterFile':
        (formData as any)[key] = []
        break
      case 'tags':
        (formData as any)[key] = []
        break
      case 'maxParticipants':
        (formData as any)[key] = 50
        break
      case 'price':
        (formData as any)[key] = 0
        break
      case 'status':
        (formData as any)[key] = 'upcoming'
        break
      default:
        (formData as any)[key] = ''
        break
    }
  })
  editIndex.value = -1
}

// 生命周期钩子
onMounted(() => {
  // 加载数据
  handleSearch()
})
</script>

<style scoped>
.activities-page {
  padding: 16px;
}

.header-card,
.search-card,
.table-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

.search-buttons {
  display: flex;
  justify-content: flex-end;
}

.activity-poster-container {
  width: 80px;
  height: 45px;
  overflow: hidden;
  border-radius: 4px;
}

.activity-poster {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.tip-text {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}
</style> 